const MonitorModel = require('../models/monitorModel');
const { getLogger } = require('../logger');
const logger = getLogger('controllers.monitorController');
const { success, error, badRequest, serverError } = require('../utils/response');
const { logAudit } = require('../utils/auditLogger');
const jwt = require("jsonwebtoken");

/**
 * 接收监控数据上报
 */
const reportMonitorData = async (req, res) => {
    try {
        
        const { sessionId, data, timestamp, url , userid =''} = req.body;
        
        // 验证必填字段
        if (!data || !Array.isArray(data)) {
            return badRequest(req, res, '数据格式错误，data必须是数组');
        }
        
        if (data.length === 0) {
            return success(req, res, '上报成功', { insertedCount: 0 });
        }

        // 从token中解析用户信息
        let userId = null;

        const accessToken = req.headers['authorization']?.split(' ')[1];
        if(accessToken){
            try {
                const decoded = jwt.verify(accessToken, process.env.JWT_SECRET);
                userId = decoded.id;
            } catch (tokenError) {
                logger.warn('Token解析失败，使用备用用户ID', { errorMessage: tokenError.message });
                // 即使token验证失败，也继续处理上报数据，不中断流程
            }
        }
        
        // 准备上报数据
        const reportData = {
            sessionId: sessionId || `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            data,
            userId:userId || userid,  // 添加用户ID支持
            timestamp: timestamp || Date.now(),
            url: url || req.headers.referer || ''
        };
        
            // 批量插入数据库
        const result = await MonitorModel.batchInsertMonitorData(reportData);
        
        // 处理不同的插入结果情况
        if (result.partialSuccess) {
            logger.info(`⚠️  监控数据部分上报成功: ${result.insertedCount}/${data.length} 条`);
            logger.error('部分失败原因', { error: result.error });
            
            // 返回部分成功的状态码，前端可以据此决定是否需要重试未成功的数据
            await logAudit(req, { action_type: 'create', module_code: 'monitor', business_type: 'report', operation_desc: 'partial', target_entity_type: 'monitor', change_summary: `partial ${result.insertedCount}/${data.length}` });
            return success(req, res, '部分数据上报成功', {
                insertedCount: result.insertedCount,
                monitorData: result.monitorData,
                behaviorEvents: result.behaviorEvents,
                performanceData: result.performanceData,
                totalCount: data.length,
                sessionId: reportData.sessionId,
                partialSuccess: true,
                message: result.error
            });
        } else {
            logger.info(`✅ 监控数据上报成功: ${result.insertedCount} 条`);
            
            await logAudit(req, { action_type: 'create', module_code: 'monitor', business_type: 'report', operation_desc: 'success', target_entity_type: 'monitor', change_summary: `inserted ${result.insertedCount}` });
            return success(req, res, '上报成功', {
                insertedCount: result.insertedCount,
                monitorData: result.monitorData,
                behaviorEvents: result.behaviorEvents,
                performanceData: result.performanceData,
                sessionId: reportData.sessionId,
                message: `成功插入 ${result.insertedCount} 条数据`
            });
        }
        
    } catch (err) {
        logger.error('❌ 监控数据上报失败', { error: err });
        return serverError(req, res, '上报失败');
    }
};

/**
 * 获取错误统计
 */
const getErrorStats = async (req, res) => {
    try {
        const { startTime, endTime } = req.query;
        
        const result = await MonitorModel.getErrorStats(startTime,endTime);
        
        return success(req, res, 'success', {
            summary: result.summary,
            details: result.details || [],
            total: result.total || 0
        });
    } catch (err) {
        logger.error('获取错误统计失败', { error: err });
        return serverError(req, res, '获取错误统计失败');
    }
};

/**
 * 获取性能统计
 */
const getPerformanceStats = async (req, res) => {
    try {
        const { startTime, endTime } = req.query;
        
        const result = await MonitorModel.getPerformanceStats(startTime,endTime);
        
        return success(req, res, 'success', {
            summary: result.summary,
            metrics: result.metrics || {},
            trends: result.trends || []
        });
    } catch (err) {
        logger.error('获取性能统计失败', { error: err });
        return serverError(req, res, '获取性能统计失败');
    }
};

/**
 * 获取用户行为统计
 */
const getBehaviorStats = async (req, res) => {
    try {
        const { startTime, endTime } = req.query;
        
        const result = await MonitorModel.getBehaviorStats(startTime,endTime);
        
        return success(req, res, 'success', {
            summary: result.summary,
            eventDetails: result.eventDetails || [],
            categorySummary: result.categorySummary || []
        });
    } catch (err) {
        logger.error('获取行为统计失败', { error: err });
        return serverError(req, res, '获取行为统计失败');
    }
};

/**
 * 获取会话列表
 */
const getSessionList = async (req, res) => {
    try {
        const {
            page = 1,
            pageSize = 20,
            startTime,
            endTime,
            userId,
            projectId,
            hasError
        } = req.query;
        
        const result = await MonitorModel.getSessionList({
            page: parseInt(page),
            pageSize: parseInt(pageSize),
            startTime,
            endTime,
            userId,
            projectId,
            hasError
        });
        
        return success(req, res, 'success', {
            list: result.list || [],
            total: result.total || 0,
            page: result.page,
            pageSize: result.pageSize
        });
    } catch (err) {
        logger.error('获取会话列表失败', { error: err });
        return serverError(req, res, '获取会话列表失败');
    }
};

/**
 * 清理过期数据
 */
const cleanExpiredData = async (req, res) => {
    try {
        // 从query或body中获取参数，兼容两种调用方式
        const days = req.body.days || req.query.days || req.body.daysToKeep || 30;
        
        if (parseInt(days) <= 0) {
            return badRequest(req, res, 'days必须是大于0的数字');
        }
        
        const result = await MonitorModel.cleanExpiredData(parseInt(days));
        
        return success(req, res, '清理成功', {
            cleanedTables: result.cleanedTables || [],
            affectedRows: result.affectedRows || result.deletedCount || 0,
            message: `成功清理 ${result.days || days} 天前的数据`
        });
    } catch (err) {
        logger.error('清理过期数据失败', { error: err });
        return serverError(req, res, '清理过期数据失败');
    }
};

/**
 * 获取操作回溯数据
 */
const getPlaybackData = async (req, res) => {
    try {
        const { sessionId, startTime, endTime, reporttype, category, sequenceId } = req.query;
        
        if (!sessionId) {
            return badRequest(req, res, 'sessionId不能为空');
        }
        
        // 兼容旧版本调用方式
        const result = await MonitorModel.getPlaybackData({
            sessionId,
            startTime,
            endTime,
            reporttype,
            category,
            sequenceId
        });
        
        return success(req, res, 'success', {
            sessionId,
            events: result.events || result.data || [],
            total: result.total || result.count || 0,
            duration: result.duration || 0,
            sequenceId
        });
    } catch (err) {
        logger.error('获取操作回溯数据失败', { error: err });
        return serverError(req, res, '获取操作回溯数据失败');
    }
};

/**
 * 获取会话详情
 */
const getSessionDetail = async (req, res) => {
    try {
        // 支持从params和query中获取sessionId，提高接口灵活性
        const sessionId = req.params.sessionId || req.query.sessionId;
        
        if (!sessionId) {
            return badRequest(req, res, 'sessionId不能为空');
        }
        
        const detail = await MonitorModel.getSessionDetail(sessionId);
        
        if (!detail) {
            return error(req, res, '会话不存在', 404);
        }
        
        return success(req, res, 'success', {
            sessionInfo: detail.sessionInfo || detail,
            errors: detail.errors || [],
            performance: detail.performance || {},
            events: detail.events || []
        });
    } catch (err) {
        logger.error('获取会话详情失败', { error: err });
        return serverError(req, res, '获取会话详情失败');
    }
};

/**
 * 获取监控数据列表
 */
const getMonitorDataList = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;

        // 构建过滤条件
        const filters = {};
        if (req.query.startTime) filters.startTime = req.query.startTime;
        if (req.query.endTime) filters.endTime = req.query.endTime;
        if (req.query.reporttype) filters.reporttype = req.query.reporttype;
        if (req.query.category) filters.category = req.query.category;
        if (req.query.type) filters.type = req.query.type;
        if (req.query.projectId) filters.projectId = req.query.projectId;
        if (req.query.userId) filters.userId = req.query.userId;
        if (req.query.sessionId) filters.sessionId = req.query.sessionId;
        if (req.query.pageUrl) filters.sequenceId = req.query.pageUrl;
        
        const result = await MonitorModel.getMonitorDataList(page, limit, filters);
        
        return success(req, res, 'success', {
            list: result.list || [],
            total: result.total || 0,
            page: result.page,
            pageSize: result.pageSize
        });
    } catch (err) {
        logger.error('获取监控数据列表失败', { error: err });
        return serverError(req, res, '获取监控数据列表失败');
    }
};

module.exports = {
    reportMonitorData,
    getMonitorDataList,
    getErrorStats,
    getPerformanceStats,
    getBehaviorStats,
    getSessionList,
    getSessionDetail,
    getPlaybackData,
    cleanExpiredData
};

